/*
 * http_c3.cpp
 *
 *  Created on: Dec 11, 2013
 *      Author: killerg
 */

#include "http_c.h"

#include "util.h"

#include <stdio.h>
#include <stdlib.h>
#include <uv.h>
#include <curl/curl.h>
#include <string.h>

struct data_t {
    std::string recv_buffer;
    std::string send_buffer;
    size_t send_len;
    http_client3::client_cb_t cb;
};

//#define USE_POOL 1

curl_context_t* create_curl_context(http_client3* cli, curl_socket_t sockfd)
{
  curl_context_t *context;

  context = (curl_context_t *) malloc(sizeof *context);

  context->sockfd = sockfd;
  context->client = cli;

  uv_poll_init_socket(cli->loop, &context->poll_handle, sockfd);
  context->poll_handle.data = context;

  return context;
}

void curl_close_cb(uv_handle_t *handle)
{
  curl_context_t* context = (curl_context_t*) handle->data;
  free(context);
}

void destroy_curl_context(curl_context_t *context)
{
  uv_close((uv_handle_t*) &context->poll_handle, curl_close_cb);
}


void add_download(const char *url, int num)
{

}

void curl_perform(uv_poll_t *req, int status, int events)
{
  int running_handles;
  int flags = 0;
  curl_context_t *context;
  char *done_url;
  CURLMsg *message;
  int pending;
  data_t* data = NULL;

  if (events & UV_READABLE)
    flags |= CURL_CSELECT_IN;
  if (events & UV_WRITABLE)
    flags |= CURL_CSELECT_OUT;

  context = (curl_context_t*)req;
  uv_timer_stop(&context->client->timeout.timer);

  curl_multi_socket_action(context->client->curl_handle, context->sockfd, flags,
                           &running_handles);

  CURLMsg msg;
  while ((message = curl_multi_info_read(context->client->curl_handle, &pending))) {
	msg = *message;
    switch (msg.msg) {
    case CURLMSG_DONE:
      --context->client->still_running;
      curl_easy_getinfo(msg.easy_handle,
              CURLINFO_PRIVATE,
              &data);
      curl_easy_getinfo(msg.easy_handle,
              CURLINFO_EFFECTIVE_URL,
              &done_url);
      curl_multi_remove_handle(context->client->curl_handle, msg.easy_handle);

#ifdef USE_POOL
      if (context->client->free_handles.size() >= 10) {
#endif
    	  curl_easy_cleanup(msg.easy_handle);
#ifdef USE_POOL
      } else {
    	  context->client->free_handles.push(message->easy_handle);
      }
#endif

      data->cb(msg.data.result, data->recv_buffer);
      safe_del(data);

      break;
    default:
      UTIL_LOG(E, "CURLMSG default");
      abort();
    }
  }
}

void on_timeout(uv_timer_t *req, int status)
{
  my_timer_t* mtimer = (my_timer_t*)req;

  int running_handles;
  curl_multi_socket_action(mtimer->client->curl_handle, CURL_SOCKET_TIMEOUT, 0, &running_handles);
}

void start_timeout(CURLM *multi, long timeout_ms, void *userp)
{
  http_client3* cli = (http_client3*)userp;
  if (timeout_ms <= 0)
    timeout_ms = 1; /* 0 means directly call socket_action, but we'll do it in
                       a bit */

  uv_timer_start(&cli->timeout.timer, on_timeout, timeout_ms, 0);
}

int handle_socket(CURL *easy, curl_socket_t s, int action, void *userp,
                  void *socketp)
{
  http_client3* cli = (http_client3*)userp;
  curl_context_t *curl_context;
  if (action & (CURL_POLL_IN|CURL_POLL_OUT)) {
    if (socketp) {
      curl_context = (curl_context_t*) socketp;
    }
    else {
      curl_context = create_curl_context(cli, s);
    }
    curl_multi_assign(cli->curl_handle, s, (void *) curl_context);
  }

  switch (action) {
  case CURL_POLL_IN:
    uv_poll_start(&curl_context->poll_handle, UV_READABLE, curl_perform);
    break;
  case CURL_POLL_OUT:
    uv_poll_start(&curl_context->poll_handle, UV_WRITABLE, curl_perform);
    break;
  case CURL_POLL_INOUT:
    uv_poll_start(&curl_context->poll_handle, UV_WRITABLE|UV_READABLE, curl_perform);
    break;
  case CURL_POLL_REMOVE:
    if (socketp) {
      uv_poll_stop(&((curl_context_t*)socketp)->poll_handle);
      destroy_curl_context((curl_context_t*) socketp);
      curl_multi_assign(cli->curl_handle, s, NULL);
    }
    break;
  default:
    abort();
  }

  return 0;
}

size_t read_cb( char *ptr, size_t size, size_t nmemb, void *userdata) {
    auto data = (data_t*)userdata;
    size_t total_size = size*nmemb;

    if (data->send_len < data->send_buffer.size()) {
        total_size = std::min(total_size, data->send_buffer.length() - data->send_len);
        memcpy(ptr, data->send_buffer.c_str() + data->send_len, total_size);
        data->send_len += total_size;
        return total_size;
    }

    return 0;
}
size_t write_cb( char *ptr, size_t size, size_t nmemb, void *userdata) {
    auto data = (data_t*)userdata;
    size_t total_size = size*nmemb;
    data->recv_buffer.append(ptr, total_size);

    return total_size;
}

bool http_client3::do_query(const char* url, const char* body, client_cb_t cb) {
    auto data = new data_t;
    data->cb = cb;
    if (body != NULL)
        data->send_buffer.append(body);
    data->send_len = 0;
    CURL* http_handle = NULL;
#ifdef USE_POOL
    if (free_handles.empty()) {
#endif
    	http_handle = curl_easy_init();
#ifdef USE_POOL
    } else {
    	http_handle = free_handles.top();
    	free_handles.pop();
    }
#endif

    if (strncmp(url, "https", 5) == 0) {
    	curl_easy_setopt(http_handle, CURLOPT_SSL_VERIFYPEER, 0L);
		curl_easy_setopt(http_handle, CURLOPT_SSL_VERIFYHOST, 0L);
    }

    curl_easy_setopt(http_handle, CURLOPT_URL, url);
    curl_easy_setopt(http_handle, CURLOPT_PRIVATE, data);
    curl_easy_setopt(http_handle, CURLOPT_WRITEFUNCTION, write_cb);
    curl_easy_setopt(http_handle, CURLOPT_READFUNCTION, read_cb);
    curl_easy_setopt(http_handle, CURLOPT_WRITEDATA, data);
    curl_easy_setopt(http_handle, CURLOPT_READDATA, data);
    if (body != NULL) {
        curl_easy_setopt(http_handle, CURLOPT_POST, 1);
        curl_easy_setopt(http_handle, CURLOPT_POSTFIELDSIZE, data->send_buffer.length());
    } else {
        curl_easy_setopt(http_handle, CURLOPT_HTTPGET, 1);
    }
    CURLMcode rt = curl_multi_add_handle(curl_handle, http_handle);

    ++still_running;
    return rt == CURLM_OK;
}

bool http_client3::init() {
    still_running = 0;
    timeout.client = this;
    loop = uv_default_loop();

    if (curl_global_init(CURL_GLOBAL_ALL)) {
      UTIL_LOG(E, "Could not init cURL");
      return false;
    }

    uv_timer_init(loop, &timeout.timer);

    curl_handle = curl_multi_init();
    curl_multi_setopt(curl_handle, CURLMOPT_SOCKETFUNCTION, handle_socket);
    curl_multi_setopt(curl_handle, CURLMOPT_SOCKETDATA, this);
    curl_multi_setopt(curl_handle, CURLMOPT_TIMERFUNCTION, start_timeout);
    curl_multi_setopt(curl_handle, CURLMOPT_TIMERDATA, this);
    curl_multi_setopt(curl_handle, CURLMOPT_PIPELINING, 0);
    curl_multi_setopt(curl_handle, CURLMOPT_MAXCONNECTS, 100);

    return true;
}
void http_client3::destroy() {
#ifdef USE_POOL
	while (!free_handles.empty()) {
		curl_easy_cleanup(free_handles.top());
		free_handles.pop();
	}
#endif
    curl_multi_cleanup(curl_handle);
    uv_loop_delete(loop);
    curl_global_cleanup();
}
void http_client3::update() {
    uv_run(loop, UV_RUN_NOWAIT);
}

